using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovedSweet : MonoBehaviour
{
    private GameSweet sweet;

    private IEnumerator moveCoroutine; //这样得到其他指令的时候可以终止协程

    private void Awake()
    {
        sweet = GetComponent<GameSweet>();
    }

    //开启或者关闭一个协程
    public void Move(int newX, int newY, float time) //将新的坐标传递给sweet
    {
        if (moveCoroutine != null)
        {
            StopCoroutine(moveCoroutine);
        }//关闭旧的协程开启新的协程  为了使目标位置随时重新指定, 比如甜品消除了,但是上面的甜品还在动,这是gmaemanager就会通知它目的改变

        moveCoroutine = MoveCoroutine(newX, newY, time);
        StartCoroutine(moveCoroutine);
    }

    //负责移动的协程
    private IEnumerator MoveCoroutine(int newX, int newY, float time)
    {
        sweet.X = newX;
        sweet.Y = newY;

        //每帧移动一点点
        Vector3 startPos = transform.position;
        Vector3 endPos = sweet.gameManager.CorrectPosition(newX, newY); //确定起点终点

        for (float t = 0; t < time; t += Time.deltaTime)
        {
            sweet.transform.position = Vector3.Lerp(startPos, endPos, t / time);//平滑的移动动画  移动当前距离的几分之几
            yield return 0;//每一帧都返回
        }

        sweet.transform.position = endPos;
    }
}